<template>
	<view class="publish-content">
		
		<view class="content-pad">
			<u--textarea 
					v-model="addPostDTO.content" 
					border="none"
					:maxlength="maxlength"
					height="160"
					confirmType="done"
					count
					:placeholder="placeholder" >
			</u--textarea>
		</view>
		<view class="content-pad">
			<u-upload
				:fileList="fileList"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				accept="image"
				multiple
				:maxCount="12"
				uploadIcon="plus"
				:previewFullImage="true"
			></u-upload>
		</view>
		<!-- 发布按钮 -->
		<view style="position: fixed;text-align: center;bottom: 20rpx;width: 100%;">
			<u-button color="#2979ff" @click="submit" customStyle="width: 400rpx;">发布</u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {getUploadToken, publishDealPost} from '@/utils/api.js'
	export default {
		data() {
			return {
				fileList: [],
				placeholder: '',
				maxlength: 120,
				addPostDTO: {
					userId: 1,
					content: '',
					imgUrls: '',
					type: '',
				},
				token: '',
				lookImgPre: '',
			}
		},
		onLoad(option) {
			uni.setNavigationBarTitle({
				title: getApp().getTypeStr(option.type)
			})
			if(option.type == 2){
				this.placeholder = '请输入要分享的内容...'
			}else {
				this.placeholder = '请输入要发布的内容...'
				this.maxlength = 800
			}
			this.addPostDTO.type = option.type
		},
		onReady() {
			if(this.addPostDTO.type == ''){
				getApp().globalData.toast[1].message = '非法访问页面!'
				this.$refs.uToast.show({
					...getApp().globalData.toast[1],
					complete() {
						uni.$u.route({
							type: 'back',
							delta: 1,
							animationType: 'pop-out',
							animationDuration: 100
						});
					}
				})
			}
			this.getToken()
		},
		methods: {
			getToken(){
				getUploadToken().then(res=>{
					this.token = res.uploadToken
					this.lookImgPre = res.lookImgPre
				}).catch(err=>{
					getApp().globalData.toast[1].message = err.message
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {
							uni.$u.route({
								type: 'back',
								delta: 1,
								animationType: 'pop-out',
								animationDuration: 100
							});
						}
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				const _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that.fileList.length
				//let fileListLen = _that[`fileList${event.name}`].length
				lists.map((item) => {
					_that.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that.fileList[fileListLen]
					if(result.hash != null){
						_that.addPostDTO.imgUrls += _that.lookImgPre + result.key + ","
						_that.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '成功',
							url: _that.lookImgPre + result.key
						}))
						fileListLen++
					}else {
						getApp().globalData.toast[1].message = '图片上传失败!'
						_that.$refs.uToast.show({
							...getApp().globalData.toast[1],
							complete() {
								_that.fileList.splice(i, 1)
							}
						})
					}
					
				}
			},
			uploadFilePromise(url) {
				const that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://upload.qiniup.com/', 
						filePath: url,
						name: 'file',
						timeout: 5000,
						formData: {
							token: that.token,
							//key: url.substr(url.indexOf("0/") + 2)
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (error) => {
							console.log("错误!", error)
							resolve(error)
						}
					});
				})
			},
			submit(){
				if(this.addPostDTO.content == ''){
					getApp().globalData.toast[1].message = '您还没有输入内容哦!'
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {}
					})
					return
				}
				let imgs = this.addPostDTO.imgUrls
				if(imgs.length > 1){
					this.addPostDTO.imgUrls = imgs.substr(0, imgs.length - 1)
				}
				const _that = this
				publishDealPost(_that.addPostDTO).then(res => {
					getApp().globalData.toast[0].message = '发布帖子成功!'
					_that.$refs.uToast.show({
						...getApp().globalData.toast[0],
						complete() {
							//当前页
							let pages = getCurrentPages()
							//上个页面
							let beforePage = pages[pages.length - 2]
							let backUrl = beforePage.route
							beforePage.$vm.getList(0)
							uni.$u.route({
								type: 'back',
								params: {
									type: _that.addPostDTO.type
								},
								delta: 1,
								animationType: 'pop-out',
								animationDuration: 200
							});
							
						}
					})
				}).catch(error=>{
					getApp().globalData.toast[1].message = error.message
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {
							uni.$u.route({
								type: 'back',
								delta: 1,
								animationType: 'pop-out',
								animationDuration: 200
							})
						},
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.publish-content{
		.content-pad{
			margin-top: 10rpx; padding: 20rpx;
		}
	}
</style>
